package com.transpot.controller.car;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.transpot.entry.car.*;
import com.transpot.entry.driver.Driver;
import com.transpot.service.car.CarDriverService;
import com.transpot.service.car.CarInformationService;
import com.transpot.service.car.CarService;
import com.transpot.service.car.InformationService;
import com.transpot.service.driver.DriverService;
import com.transpot.utils.R;
import com.transpot.utils.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {
    @Autowired
    private CarService carService;
    @Autowired
    private InformationService informationService;
    @Autowired
    private CarInformationService carInformationService;
    @Autowired
    private CarDriverService carDriverService;
    @Autowired
    private DriverService driverService;

    /**
     * 车辆注册的controller层接口方法
     * @param carJSON
     * @param file1
     * @param file2
     * @param file3
     * @return
     */
    @PostMapping("/registerCar")
    public R registerCar(@RequestParam("car") String carJSON, @RequestParam("file1") MultipartFile file1,
                         @RequestParam("file2") MultipartFile file2, @RequestParam("file3") MultipartFile file3) {
        //创建json转化对象
        ObjectMapper mapper = new ObjectMapper();
        //把json字符串转换成对象
        Car car = null;
        try {
            car = mapper.readValue(carJSON, Car.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //创建车辆照片信息类对象
        Information information = new Information();
        //调用图片上传方法上传图片
        if (!file1.isEmpty()) {
            //调用方法将图片上传，得到图片返回路径
            String imgUrl1 = UploadUtil.uploadImg(file1);
            //将图片路径存入图片信息对象中
            information.setImgUrl1(imgUrl1);
        }
        if (!file2.isEmpty()) {
            String imgUrl2 = UploadUtil.uploadImg(file2);
            information.setImgUrl2(imgUrl2);
        }
        if (!file3.isEmpty()) {
            String imgUrl3 = UploadUtil.uploadImg(file3);
            information.setImgUrl3(imgUrl3);
        }
        //调用service层方法存入车辆照片信息
        informationService.save(information);
        //调用service层方法存入车辆信息
        carService.registerCar(car);
        //创建车辆图片信息和车辆信息的中间类对象
        CarInformation carInformation = new CarInformation();
        //设置车辆主键
        carInformation.setCarId(car.getId());
        //设置车辆图片信息主键
        carInformation.setInformationId(information.getId());
        //调用service层方法存入中间类对象
        carInformationService.save(carInformation);
        return R.success();
    }

    /**
     * 获取全部属于公司的汽车的方法
     * @return
     */
    @GetMapping("/getAllCarWithCompany")
    public R getAllCarWithCompany() {
        //创建条件查询对象
        LambdaQueryWrapper<Car> carLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置条件为所有人是公司
        carLambdaQueryWrapper.eq(Car::getPeople, "公司");
        //查询所有的汽车
        List<Car> carList = carService.list(carLambdaQueryWrapper);
        //返回结果给前端
        return R.success(carList);
    }

    /**
     * 分页条件查询车辆信息接口方法
     * @param current
     * @param size
     * @param number
     * @param age
     * @param carLength
     * @param load
     * @param type
     * @param engineNo
     * @param people
     * @return
     */
    @GetMapping("/getCarByPageAndCondition")
    public R getCarByPageAndCondition(int current, int size, String number,Integer age,
                                      Integer carLength, Integer load, String type,
                                      String engineNo, String people) {
        //创建分页查询对象
        IPage<Car> iPage = new Page<>(current, size);
        //创建条件查询对象
        LambdaQueryWrapper<Car> carLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件，当条件不为空时添加条件
        carLambdaQueryWrapper.eq(StringUtils.isNotBlank(number), Car::getNumber, number)
                .eq(age != null, Car::getAge, age)
                .eq(carLength != null, Car::getCarLength, carLength)
                .eq(load != null, Car::getLoad, load)
                .eq(StringUtils.isNotBlank(type), Car::getType, type)
                .eq(StringUtils.isNotBlank(engineNo), Car::getEngineNo, engineNo)
                .eq(StringUtils.isNotBlank(people), Car::getPeople, people);
        //分页查询车辆基本信息
        carService.page(iPage, carLambdaQueryWrapper);
        //根据车辆基本信息获取CarVO分页对象
        Page<CarVO> carVOPage = carService.getCarVO(iPage);
        //返回给前端
        return R.success(carVOPage);
    }

    /**
     * 获取和车辆关联的司机信息
     * @param id
     * @return
     */
    @GetMapping("/getCarDriver")
    public R getCarDriver(Integer id) {
        //创建条件查询对象
        LambdaQueryWrapper<CarDriver> carDriverLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件为和车辆主键一致
        carDriverLambdaQueryWrapper.eq(CarDriver::getCarId, id);
        //查询该车辆与司机的关联
        List<CarDriver> carDriverList = carDriverService.list(carDriverLambdaQueryWrapper);
        //创建司机列表用来存储数据
        List<Driver> driverList = new ArrayList<>();
        //遍历所有的车辆和司机的关联
        for (CarDriver carDriver : carDriverList) {
            //获取到司机的主键
            Integer driverId = carDriver.getDriverId();
            //根据司机主键查询司机信息
            Driver driver = driverService.getById(driverId);
            //把司机信息添加到列表里
            driverList.add(driver);
        }
        //返回结果
        return R.success(driverList);
    }

    /**
     * 删除车辆信息
     * @param id
     * @return
     */
    @DeleteMapping("/deleteCar")
    public R deleteCar(Integer id) {
        carService.deleteCarById(id);
        return R.success();
    }

    /**
     * 修改车辆信息方法（修改图片）
     * @return
     */
    @PostMapping("/updateCarAndInformation")
    public R updateCarAndInformation(@RequestParam("cars") String carJson, @RequestParam("file[]") MultipartFile[] files) {
        //创建json转化对象
        ObjectMapper mapper = new ObjectMapper();
        //因为java8的日期类型jackson不能转化因此要加一个时间模块
        mapper.registerModule(new JavaTimeModule());
        //把json字符串转换成对象
        CarVO carVO = null;
        try {
            carVO = mapper.readValue(carJson, CarVO.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //调用service层方法处理数据完成修改
        carService.updateWithPicture(carVO, files);
        return R.success();
    }

    /**
     * 修改车辆信息方法（不修改图片）
     * @return
     */
    @PostMapping("/updateCar")
    public R updateCar(@RequestBody CarVO carVO) {
        //创建车辆信息对象
        Car car = new Car();
        //把carVO对象的属性赋值给car对象
        BeanUtils.copyProperties(carVO, car);
        //设置上次修改时间为当前
        car.setUpdateTime(LocalDateTime.now());
        //修改车辆信息
        carService.updateById(car);
        //返回结果
        return R.success();
    }

    /**
     * 根据登录的角色的id获取到与之关联的车辆信息
     * @param id
     * @return
     */
    @GetMapping("/getCarListById")
    public R getCarListById(Integer id) {
        //调用service层方法封装数据返回
        List<CarVO> carVOList = carService.getCarListById(id);
        //返回数据
        return R.success(carVOList);
    }
}
